<?php

namespace App\Exports;

use App\Enums\OrderStatus;
use App\Models\Download;
use App\Models\FrontendUser;
use App\Models\Order;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class ChannelOrderExport implements FromQuery, WithMapping, WithHeadings
{
    public $data;
    public $request;

    public function __construct(Download $data)
    {
        $this->data = $data;
        $this->request = json_decode($this->data->request, true);
    }

    public function query() // 返回的数据
    {
        $userIds = FrontendUser::query()->where('channel_id', $this->request['channel_id'])->pluck('id');

        return Order::query()
            ->with(['user', 'payment'])
            ->whereIn('user_id', $userIds)
            ->when(!empty($this->request['start_date']), function ($q) {
                return $q->whereDate('created_at', '>=', $this->request['start_date']);
            })
            ->when(!empty($this->request['end_date']), function ($q) {
                return $q->whereDate('created_at', '<=', $this->request['end_date']);
            })
            ->where('order_status', OrderStatus::PAID())
            ->where('agent_id', $this->data->agent_id)
            ->orderByDesc('id')->limit(30000);
    }

    public function map($value): array // 指定excel中每一列的数据字段
    {
        if ('cancel' == $value['order_status']->value) {
            $order_status = '已取消';
        } elseif ('paid' == $value['order_status']->value) {
            $order_status = '已支付';
        } elseif ('not_pay' == $value['order_status']->value) {
            $order_status = '未支付';
        } else {
            $order_status = '超时取消';
        }

        return [
            $value['id'],
            $value['order_no'],
            $value['product_name'],
            ' ' . $value['user']['mobile'] ?? '',
            $value['order_amount'] / 100 ?? 0,
            $value['created_at'],
            $order_status,
        ];
    }

    public function headings(): array // 指定excel的表头
    {
        return [
            'ID',
            '订单号',
            '产品名称',
            '购买人',
            '金额',
            '下单时间',
            '订单状态',
        ];
    }
}
